package com.bootdo.ocr.xfyun.api;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class XunFeiYunClient {
    // OCR webapi 接口地址
    private static final String WEBOCR_URL = "http://webapi.xfyun.cn/v1/service/v1/ocr/general";
    // 应用ID (必须为webapi类型应用，并印刷文字识别服务，参考帖子如何创建一个webapi应用：http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481)
    private  String appId = "5d54bda4";
    // 接口密钥(webapi类型应用开通印刷文字识别服务后，控制台--我的应用---印刷文字识别---服务的apikey)
    private String apiKey = "069d150f9a866fcb923a528bfd7b88f6";
    // 是否返回位置信息
    private static final String LOCATION = "false";
    // 语种(可选值：en（英文），cn|en（中文或中英混合)
    private static final String LANGUAGE = "cn|en";
    // 图片地址,图片最短边至少15px，最长边最大4096px，格式jpg、png、bmp


    public XunFeiYunClient(String appId, String apiKey) {
        this.appId = appId;
        this.apiKey = apiKey;
    }

    /**
     * OCR WebAPI 调用示例程序
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // 接口密钥(webapi类型应用开通印刷文字识别服务后，控制台--我的应用---印刷文字识别---服务的apikey)
        String appId = "5d54bda4";
        String apiKey = "069d150f9a866fcb923a528bfd7b88f6";
        XunFeiYunClient client = new XunFeiYunClient(appId, apiKey);
        String path = "D:\\document\\png\\GB 13486-2000.png";
        System.out.println("OCR WebAPI 接口调用结果：" + client.fetchOcrApi(path));

    }

    /**
     * 错误码链接：https://www.xfyun.cn/document/error-code (code返回错误码时必看)
     * @param filePath
     * @return
     * @throws IOException
     */
    public  String fetchOcrApi(String filePath) {
        String response = "";
        try {
            Map<String, String> header = buildHttpHeader(apiKey, appId);
            byte[] imageByteArray = FileUtils.readFileToByteArray(new File(filePath));
            String imageBase64 = new String(Base64.encodeBase64(imageByteArray), "UTF-8");
            response = HttpUtil.doPost1(WEBOCR_URL, header, "image=" + URLEncoder.encode(imageBase64, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
    /**
     * 组装http请求头
     */
    private  Map<String, String> buildHttpHeader(String apiKey, String appId) throws UnsupportedEncodingException {
        String curTime = System.currentTimeMillis() / 1000L + "";
        String param = "{\"location\":\"" + LOCATION + "\",\"language\":\"" + LANGUAGE + "\"}";
        String paramBase64 = new String(Base64.encodeBase64(param.getBytes("UTF-8")));
        String checkSum = DigestUtils.md5Hex(apiKey + curTime + paramBase64);
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        header.put("X-Param", paramBase64);
        header.put("X-CurTime", curTime);
        header.put("X-CheckSum", checkSum);
        header.put("X-Appid", appId);
        return header;
    }
}
